define([
    'jqueryui',
    'ionic',
    'angularDrapDrop',
    'ios9Patch',
    'ngCordova',
    'ionicU9',
    'js/controllers/controllers.main',
    'js/services/services.main',
    'js/directives/directives.main',
    'js/utility/utility.main'
], function () {
    angular.module('U9Mobile', [
        'ionic',
        'ngIOS9UIWebViewPatch',
        'ngCordova',
        'ngDragDrop',
        'ionicU9',

        'U9Mobile.controllers',
        'U9Mobile.services',
        'U9Mobile.directives',
        'U9Mobile.utility'
    ])
        .run(['$ionicHistory', '$ionicPlatform', '$timeout', 'ExtService', 'ConnectService', 'UserService', 'AppManager', 'UtilService', 'FileStorage', 'AppConstants', 'Push',
            function ($ionicHistory, $ionicPlatform, $timeout, ExtService, ConnectService, UserService, AppManager, UtilService, FileStorage, AppConstants, Push) {
                ionic.Platform.isFullScreen = true;
                function onOpenNotification(event) {
                    try {
                        if(device.platform=='Android'){
                            Push.callback(window.plugins.jPushPlugin.openNotification.extras["cn.jpush.android.EXTRA"]);
                        }
                        if(window.plugins.jPushPlugin.isPlatformIOS()){
                            var badge=parseInt(event.aps.badge)-1;
                            window.plugins.jPushPlugin.setBadge(badge);
                            window.plugins.jPushPlugin.setApplicationIconBadgeNumber(badge);
                            Push.callback(event);
                        }

                    } catch (err) {
                        alert("error" + err.message);
                    }

                }
                function onTagsWithAlias(event){
                    try{
                        console.log("onTagsWithAlias");
                        var result="result code:"+event.resultCode+"";
                        result+="tags:"+event.tags+"";
                        result+="alias:"+event.alias+" ";

                    }catch(e){
                        console.log(e);
                    }
                }
                function onReceiveNotification(event){
                    try {
                        var alerts="",obj={};
                        if(device.platform=='Android'){
                            alerts=window.plugins.jPushPlugin.receiveNotification.alert;
                            obj=window.plugins.jPushPlugin.receiveNotification.extras["cn.jpush.android.EXTRA"];
                        }
                        if(window.plugins.jPushPlugin.isPlatformIOS()){
                            var badge=parseInt(event.aps.badge)-1;
                            window.plugins.jPushPlugin.setBadge(badge);
                            window.plugins.jPushPlugin.setApplicationIconBadgeNumber(badge);
                            alerts=event.aps.alert;
                            obj=event;

                        }
                        UtilService.confirm(alerts,'新消息').then(function(res){
                            if(res){
                                Push.callback(obj);
                            }else{
                                return false;
                            }
                        })
                    } catch (err) {
                        alert("error" + err.message);
                    }
                }
                $ionicPlatform.ready(function () {
                    if (window.cordova && window.cordova.plugins.Keyboard) {
                        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                        cordova.plugins.Keyboard.disableScroll(true);
                        window.plugins.jPushPlugin.init();
                        UserService.loginPromise.then(function (userInfo) {
                            if(userInfo.autologin){
                                Push.setAlis(UserService.getPushConfig());
                            }
                        });
                        document.addEventListener("jpush.openNotification", onOpenNotification, false);
                        document.addEventListener("jpush.setTagsWithAlias",onTagsWithAlias,false);
                        document.addEventListener("jpush.receiveNotification",onReceiveNotification,false);
                        if(device.platform=='Android'){
                            uninstall.isInstalled("com.yonyouup.u9mobile",function(){
                                uninstall.remove("com.yonyouup.u9mobile",function(){

                                },function(){

                                })
                            },function(err){
                               console.log("此包不存在")
                            })
                        }
                    }
                    if (window.StatusBar) {
                        StatusBar.styleDefault();
                    }
                    FileStorage.loadingPromise.then(function () {
                        ExtService.publishExternalAPI();
                        AppManager.checkAppUpdate();
                        if (navigator.splashscreen) {
                            $timeout(function () {
                                navigator.splashscreen.hide();
                            }, AppConstants.SPLASH_SCREEN_EXTRA_DELAY);
                        }
                    });
                });

                $ionicPlatform.on('offline', function () {
                    UtilService.toastLongCenter('网络已断开，请连接网络！');
                }, false);
                if (ionic.Platform.isIOS()) {
                    $ionicPlatform.on('resume', function () {
                        readJumpLandingConfig();
                    }, false);
                }
                $ionicPlatform.registerBackButtonAction(
                    onHardwareBackButton,
                    AppConstants.PLATFORM_BACK_BUTTON_PRIORITY_VIEW
                );
                var confirmExit = false;

                function onHardwareBackButton(e) {
                    if ($ionicHistory.currentStateName() !== 'app.home') {
                        UtilService.goState('app.home');
                    } else if ($ionicHistory.backView()) {
                        $ionicHistory.goBack();
                    } else {
                        if (confirmExit) {
                            ionic.Platform.exitApp();
                        } else {
                            confirmExit = true;
                            UtilService.toastShortBottom(AppConstants.EXIT_APP_CONFIRM_STR);
                            $timeout(function () {
                                confirmExit = false;
                            }, AppConstants.EXIT_APP_CONFIRM_TIME);
                        }
                    }

                    e.preventDefault();
                    return false;
                }

                function readJumpLandingConfig() {
                    window.Analytics.analytics("login", "main", function (data) {
                        if (data.hasOwnProperty("account") && data.account.length > 0) {
                            myAnalytics(data);
                        }
                    });
                }

                function myAnalytics(data) {
                    ConnectService.setConnect(data.address, data.port, '').then(function () {
                        UserService.setUserParams({
                            account: data.account,
                            password: data.password
                        });
                        UserService.login({
                            account: UserService.getUserParams('account'),
                            password: UserService.getUserParams('password'),
                            autologin: UserService.getUserParams('autologin'),
                            rememberpsw: UserService.getUserParams('rememberpsw')
                        }).then(function () {
                            if (data.status_code === "200" && data.access_token) {
                                UtilService.goState('app.home');
                            } else {
                                UtilService.alert(data.status_message);
                            }
                        });
                    });
                }
            }
        ])

        .config(['$stateProvider', '$urlRouterProvider', '$ionicConfigProvider', '$sceDelegateProvider',
            function ($stateProvider, $urlRouterProvider, $ionicConfigProvider, $sceDelegateProvider) {
                $stateProvider
                    .state('app', {
                        url: '/app',
                        abstract: true,
                        templateUrl: 'tpls/app.html',
                        controller: 'AppCtrl'
                    })
                    .state('app.home', {
                        url: '/home',
                        templateUrl: 'tpls/home.html',
                        controller: 'HomeCtrl',
                        resolve: {
                            'loadingConfig': ['$q', '$ionicHistory', 'FileStorage', 'ConnectService', 'UtilService',
                                function ($q, $ionicHistory, FileStorage, ConnectService, UtilService) {
                                    var defer = $q.defer();

                                    $ionicHistory.clearCache(['app.temp']);

                                    FileStorage.loadingPromise.then(function () {
                                        if (!ConnectService.getConnect('address') || !ConnectService.getConnect('port')) {
                                            UtilService.goState('app.connect');
                                            UtilService.tipsBottom('请先配置连接设置');
                                        }
                                        defer.resolve(true);
                                    }, function () {
                                        defer.resolve(true);
                                    });

                                    return defer.promise;
                                }
                            ]
                        }
                    })
                    .state('app.relist', {
                        url: '/relist',
                        templateUrl: 'tpls/relist.html',
                        controller: 'ReListCtrl'
                    })
                    .state('app.connect', {
                        url: '/connect',
                        templateUrl: 'tpls/connect.html',
                        controller: 'ConnectCtrl'
                    })
                    .state('app.login', {
                        url: '/login',
                        templateUrl: 'tpls/login.html',
                        controller: 'LoginCtrl'
                    })
                    .state('app.download', {
                        url: '/download',
                        templateUrl: 'tpls/download.html',
                        controller: 'DownloadCtrl'
                    })
                    .state('app.temp', {
                        url: '/temp/:param',
                        templateUrl: 'tpls/temp.html',
                        controller: 'TempCtrl'
                    })
                    .state('app.chat', {
                        url: '/chat?fromApp',
                        templateUrl: function (params) {
                            if (params.fromApp === 'true') {
                                return 'tpls/dudu/tempChat.html';
                            } else {
                                return 'tpls/dudu/appChat.html';
                            }
                        },
                        controller: 'ChatCtrl'
                    })
                    .state('app.setting', {
                        url: '/setting',
                        cache: false,
                        templateUrl: 'tpls/setting.html',
                        controller: 'SettingCtrl'
                    })
                    .state('app.user', {
                        url: '/user',
                        templateUrl: 'tpls/user.html',
                        controller: 'UserCtrl'
                    })
                    .state('app.about', {
                        url: '/about',
                        templateUrl: 'tpls/about.html',
                        controller: 'AboutCtrl'
                    })
                    .state('app.insetpage', {
                        url: '/insetpage?pageId',
                        templateUrl: 'tpls/insetpage.html',
                        controller: 'InsetPageCtrl'
                    });
                $urlRouterProvider.otherwise('/app/home');

                $sceDelegateProvider.resourceUrlWhitelist([
                    'self',
                    'http://m.u9hub.com/**'
                ]);

                $ionicConfigProvider.platform.android.navBar.alignTitle('center');
                $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
                $ionicConfigProvider.platform.android.navBar.transition('view');
                $ionicConfigProvider.platform.android.views.transition('ios');
                $ionicConfigProvider.platform.android.views.swipeBackEnabled(false);
                $ionicConfigProvider.platform.android.tabs.style('standard');
                $ionicConfigProvider.platform.android.tabs.position('bottom');
                $ionicConfigProvider.platform.android.form.toggle('large');
                $ionicConfigProvider.platform.android.form.checkbox('circle');

                $ionicConfigProvider.platform.default.views.swipeBackEnabled(false);
                $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
                $ionicConfigProvider.platform.default.backButton.text(false);
            }
        ]);
});